package com.bgybmi.util;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.jfinal.qyweixin.sdk.api.JsTicket;
import com.jfinal.qyweixin.sdk.api.JsTicketApi;
import com.jfinal.qyweixin.sdk.api.JsTicketApi.JsApiType;

/**
 * @author hecore
 * @description jstiket get by time
 * @set private maybe could
 * @base time limit
 * @issuse zone maybe cause invalid jsticket
 * @单例不适合多个应用使用
 */
public class JsTikcetCon {
    //缓存accessToken 的Map,map中包含 一个accessToken 和 缓存的时间戳
    private Map<String, String> map = new HashMap<String,String>();
    private JsTikcetCon() {
        
    }
    private static JsTikcetCon single = null;

    // 静态工厂方法
    public static JsTikcetCon getInstance() {
        if (single == null) {
            single = new JsTikcetCon();
        }
        return single;
    }

    public Map<String, String> getMap() {
        return map;
    }

    public void setMap(Map<String, String> map) {
        this.map = map;
    }

    public static JsTikcetCon getSingle() {
        return single;
    }

    public static void setSingle(JsTikcetCon single) {
    	JsTikcetCon.single = single;
    }
    
    /**
     * 获取 accessToken Jsapi_ticket 已加入缓存机制
     * @param appid
     * @param appsecret
     * @return
     */
    public String getAccessTokenAndJsapiTicket() {
        String result=null;
        JsTikcetCon singleton = JsTikcetCon.getInstance();
        Map<String, String> map = singleton.getMap();
        String time = map.get("time");//从缓存中拿数据
        String accessToken = map.get("access_token");//从缓存中拿数据
        String jsapiticket = map.get("jsapiticket");//从缓存中拿数据
        Long nowDate = new Date().getTime();
        //这里设置过期时间 3000*1000就好了
        if (time != null && nowDate - Long.parseLong(time) < 3000 * 1000) {
            System.out.println("-----从缓存读取access_token："+accessToken);
            result=jsapiticket;
        } else {
            JsTicket jsApiTicket= JsTicketApi.getTicket(JsApiType.jsapi);
    		String jsapi_ticket = jsApiTicket.getTicket();
            		//JsdkUtil.getJsapiticket(appid, appsecret);//实际中这里要改为你自己调用微信接口去获取accessToken和jsapiticket
            //将信息放置缓存中
    		map.put("jsapiticket", jsapiticket);
            result=jsapi_ticket;
            //为返回结果赋值
        }
        return result;
    }

}

